package com.yupi.project.Filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

@Slf4j
@Component
public class SimpleGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 请求前日志
        log.info("😁 请求进入: {} {} | 参数: {}",
                request.getMethod(),
                request.getURI(),
                request.getQueryParams());
        //鉴权认证

        return chain.filter(exchange)
                .doOnSuccess(aVoid -> {
                    // 成功时的日志
                    URI forwardUrl = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
                    log.info("✅ 转发成功: {} | 请求头: {}",
                            forwardUrl,
                            exchange.getRequest().getHeaders().toSingleValueMap());
                })
                .doOnError(throwable -> {
                    // 失败时也要打印转发信息
                    URI forwardUrl = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
                    log.error("❌ 转发失败: {} | 错误: {}",
                            forwardUrl,
                            throwable.getMessage());
                });
    }

    @Override
    public int getOrder() {
        return -1;
    }
}